iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 15
0
自我挑戰組

Some thing with Reason系列 第 15

研究 - bs-mongodb

  • 分享至 

  • xImage
  •  

MongoDB

先來寫個簡單的 Javascript 版本 CRUD 之前先參考 bs-mongodb

但是要先寫一個 CRUD JS 版本範例

mongodbManager.js


const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'myproject';

class mongoDBManagerClass {
  initialDB({url, dbName}){
    return MongoClient.connect(url, { useNewUrlParser: true })
    .then(client => {

      this._client = client;
      this._db = client.db(dbName);
      this._document = this._db.collection('documents');
    });
  }
  
  insertManyDocument(array) {
    return this._document.insertMany(array);
  }

  findDocuments(query) {
    return this._document.find({});
  }

  updateDocuments(query, updateQuery) {
    return this._document.update(query, updateQuery);
  }

  deleteDocuments(query) {
    return this._document.deleteMany(query);
  }

  closeClient() {
    this._client.close();
  }
}

const mongoDBManager = new mongoDBManagerClass({url, dbName});

module.exports = mongoDBManager;

app.js

const mongoDBManager = require('./mongodbManager');

mongoDBManager
  .initialDB({url, dbName})
  .then(() => mongoDBManager.insertManyDocument([{a : 1}]))
  .then((resp) => console.log(resp))
  .then(() => mongoDBManager.updateDocuments({a: 1}, {a: 2}))
  .then((resp) => console.log(resp))
  .then(() => mongoDBManager.findDocuments({a: 2}))
  .then((resp) => console.log(resp))
  .then(() => mongoDBManager.deleteDocuments({a: 2}))
  .then((resp) => console.log(resp))
  .then(() => mongoDBManager.closeClient())
  .catch(error => console.log("error", error));

上述例子是一個簡單的 MongoDBCRUD

再來慢慢將它轉為 MongoDBManager.re

先初始化一個 MongoClient


上一篇
BuckleScript-Function
下一篇
External Promise API
系列文
Some thing with Reason30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言